package com.rainng.coursesystem.service;

import okhttp3.*;
import org.json.JSONObject;
import org.json.JSONArray;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class BaiduApiService {

    private static final String API_KEY = "Rr8UUFnfN49FVACqlWCDl0Me";
    private static final String SECRET_KEY = "whQQLIJu1ofQWP2bfFRB8dSaI30AhOMd";
    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient();

    public String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            return new JSONObject(response.body().string()).getString("access_token");
        }
    }

    public String callApi(String userInput) throws IOException {
        String accessToken = getAccessToken();
        MediaType mediaType = MediaType.parse("application/json");

        // 构造请求体，包含 messages 数组
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("messages", new JSONArray()
                .put(new JSONObject().put("role", "user").put("content", userInput))
        );

        RequestBody body = RequestBody.create(mediaType, jsonObject.toString());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();

        try (Response response = HTTP_CLIENT.newCall(request).execute()) {
            return response.body().string();  // 返回API的响应内容
        }
    }

}

